package com.zb.tcp.rpc.server;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;

import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.msgpack.template.ListTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zb.dao.ext.dic.OmsDicCityCodeDao;
import com.zb.dao.ext.system.OmsNormalSpListRepo;
import com.zb.dao.ext.system.OmsOperMerchantDao;
import com.zb.dao.ext.system.OmsOperationSpListRepo;
import com.zb.entity.base.JsonCommon;
import com.zb.entity.base.JsonForList;
import com.zb.entity.base.OmsPartner;
import com.zb.entity.base.OmsPartnerType;
import com.zb.entity.charger.OmsCharger;
import com.zb.entity.charger.OmsChargerBespeakBillRecord;
import com.zb.entity.charger.OmsChargerBuildApply;
import com.zb.entity.charger.OmsChargerChargeBillRecord;
import com.zb.entity.charger.OmsChargerNo;
import com.zb.entity.charger.OmsChargerRate;
import com.zb.entity.charger.OmsChargerStateAlternate;
import com.zb.entity.charger.OmsChargerStateDirect;
import com.zb.entity.exception.BizException;
import com.zb.entity.station.*;
import com.zb.entity.system.OmsOperMerchant;
import com.zb.entity.system.OmsOperationSpListEntity;
import com.zb.service.base.DeviceTypeService;
import com.zb.service.base.ErrorTypeService;
import com.zb.service.base.OmsStationLocationService;
import com.zb.service.base.PartnerService;
import com.zb.service.base.PartnerTypeService;
import com.zb.service.base.StationCollectService;
import com.zb.service.base.StationCorrectListService;
import com.zb.service.imp.middleware.MessageAnalysisHelper;
import com.zb.service.imp.middleware.notify.app.NotifyAppServer;
import com.zb.service.imp.middleware.vo.ProtocolVersion;
import com.zb.service.imp.middleware.vo.UnSendingMessage;
import com.zb.service.middleware.OmsBespeakService;
import com.zb.service.middleware.OmsCharStationService;
import com.zb.service.middleware.OmsChargeService;
import com.zb.service.sys.BillService;
import com.zb.service.sys.ChargerService;
import com.zb.service.sys.QiniuService;
import com.zb.service.sys.StationExternalService;
import com.zb.service.sys.StationService;
import com.zb.tcp.rpc.as.client.constant.AppServerConstant;
import com.zb.tcp.rpc.os.OrderRpcClient;
import com.zb.tcp.socket.MessageFuture;
import com.zb.util.OmsConstant;
import com.zb.util.StringUtil;
import com.zb.util.OmsConstant.MsgCodeEnum;
import com.zb.util.OrderConstant.BizSystemCode;
import com.zb.util.OrderConstant.OrderServiceEnum;
import com.zb.vo.os.OrderBaseData;
import com.zb.vo.os.RetVO;
/**
 * @author qintang
 * RPC handler for App Server
 */
//@Component
public class ASRPCHandler implements RPCHandler {

	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

	private final static int maxWaitMillsec = 15000;

	private Method[] allMethods;
	@Autowired
	public PartnerTypeService partnerTypeService;
	@Autowired
	public OmsChargeService omsChargeService;
	@Autowired
	public ChargerService chargerService;
	@Autowired
	public StationService stationService;
	@Autowired
	public BillService billService;
	@Autowired
	public StationCollectService stationCollectService;
	@Autowired
	public OmsBespeakService omsBespeakService;
	@Autowired
	public PartnerService partnerService;
	@Autowired
	public StationCorrectListService stationCorrectListService;
	@Autowired
	public ErrorTypeService errorTypeService;
	@Autowired
	public OmsStationLocationService omsStationLocationService;
	@Autowired
	public DeviceTypeService deviceTypeService;
	@Autowired
	OmsOperMerchantDao 	omsOperMerchantDao;
//	@Autowired
//	OrderRpcClient orderRpcClient;
	@Autowired
	StationExternalService stationExtenrnalService;
	@Autowired
	OmsCharStationService omsCharStationService;
	@Autowired
	OmsOperationSpListRepo omsOperationSpListRepo;

//	@Value(value="${rpc.upload.imagePath}")
//	private String uploadImagePath;
	@Autowired
	QiniuService qiniuService;
	
	private static ExecutorService receiveExecutorService = Executors.newCachedThreadPool();
	private Log log = LogFactory.getLog(ASRPCHandler.class);
	
	@PostConstruct
	public void init(){
		allMethods = this.getClass().getMethods();
	}

	@Override
	public Object doProcess(String messageName, GenericRecord req) {
		if(req==null){
			req = (GenericRecord) new GenericData();
		}
		try
		{
			for(Method method :allMethods){
				if(method.getName().equals(messageName)){
					return JSON.toJSONString(method.invoke(this,req),SerializerFeature.WriteMapNullValue);
				}
			}
			return JSON.toJSONString( new JsonCommon<String>(MsgCodeEnum.AS_RPC_PARAM_FORMAT_ERROR.getMsgCode(), 
					MsgCodeEnum.AS_RPC_PARAM_FORMAT_ERROR.getMsgInfo()));

		}
//		catch (BizException e)
//		{
//			return JSON.toJSONString( new JsonCommon<>(e.getErrorCode(), e.getMessage()));
//		}
		catch (Exception e)
		{
			log.error(e.getMessage(), e);
			Throwable t = e.getCause();
			while (t.getCause() != null)
				t = t.getCause();
			if (t instanceof BizException && ((BizException) t).getErrorCode() != null)
				return JSON.toJSONString(new JsonCommon<>(((BizException) t).getErrorCode(), e.getCause().getMessage()));
			return JSON.toJSONString(new JsonCommon<String>(MsgCodeEnum.AS_RPC_SERVER_ERROR.getMsgCode(), e.getMessage()));
		}

	}


	/**
	 * 申请合作类型查询
	 * @param request null
	 * @return JsonForList<OmsPartnerType> 合作类型
	 */
	@SuppressWarnings("rawtypes")
	public JsonForList cooperationType(GenericRecord request){
		JsonForList<OmsPartnerType> retJsons = new JsonForList<OmsPartnerType>();
		retJsons.setList(partnerTypeService.findAll());
		return retJsons;
	}
	
	/**
	 * 申请合作
	 * @param request {"cooperationTypeId":"合作类型Id"
	 *                  "userId":"用户ID"}
	 * @return JsonCommon<String> "OK"
	 * @throws Exception 
	 */
	public JsonCommon applyCooperation(GenericRecord request) throws Exception{
		String type_id  = request.get("cooperationTypeId").toString();
		String partner_id = request.get("userId").toString();
		if(partner_id==null||"".equals(partner_id)||type_id==null||"".equals(type_id)){
			throw new Exception("call parameter error:partner_id:"+partner_id+" type_id:"+type_id );
		}
		JsonCommon<String> retJson = new JsonCommon<String>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.AS_RPC_PARAM_SUCCESS.getMsgInfo());
		OmsPartner newPartner = new OmsPartner();
		newPartner.setPartner_id(Integer.valueOf(partner_id).intValue());
		newPartner.setType_id(Integer.valueOf(type_id).intValue());
		this.partnerService.add(newPartner);
		return retJson;
	}
	
	/**
	 * 数据包更新接口
	 * @param request {"province_code": "省代码"}
	 * @return JsonForList<OmsStation> 
	 * @throws Exception
	 * @modify 张金荣
	 */
	public JsonForList updateMapDataPackage(GenericRecord request) throws Exception {
		String province_code = request.get("provinceCode").toString();
		if(province_code==null||"".equals(province_code)){
			throw new Exception("call parameter error:province_code:"+province_code);
		}
		JsonForList<OmsStation> retJsons = new JsonForList<OmsStation>();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		List<OmsStation> lsStations = this.stationService.getStationByDistrictCode(province_code, null, null);
		/*for(OmsStation station:lsStations){
			List<OmsStationLocation> lsStationLoc = this.omsStationLocationService.findValidByStationId(station.getStation_id());
			station.setLocationList(lsStationLoc);
		}
		for(int i=0;i<lsStations.size();i++){
			lsStations.get(i).setLocationList(this.omsStationLocationService.findValidByStationId(lsStations.get(i).getStation_id()));
		}*/
		ListIterator<OmsStation> iterator=lsStations.listIterator(lsStations.size());
		while(iterator.hasPrevious()){
			OmsStation omsStation = iterator.previous();
            List<OmsStationLocation> lsStationLoc = this.omsStationLocationService.findValidByStationId(omsStation.getStation_id());
			if(lsStationLoc.size()>0){
				omsStation.setLocationList(lsStationLoc);
				if(StringUtil.isNotBlank(omsStation.getDistrict_code())){
					//省编码为区县编码的前两位+0000 构成
					omsStation.setProvince_code(omsStation.getDistrict_code().substring(0, 2)+"0000");
				} 
			}else {
				iterator.remove();
			}	
        }
		retJsons.setList(lsStations);
		return retJsons;

	}
	
	
	/**
	 * 获取当前正在充电或预约的数量接口
	 * @param request {userCard:用户卡号}
	 * @return JsonCommon<OmsChargerNo>: 电桩记录实体类
	 */
	public JsonCommon getCurrentUseBookOrChargeNumbers(GenericRecord request) throws Exception {
		String userCard =  request.get("userCard").toString();
		if(userCard==null||"".equals(userCard)){
			throw new Exception("call parameter error:userCard:"+userCard);
		}
		JsonCommon<OmsChargerNo> retJson = new JsonCommon<OmsChargerNo>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		
		JsonCommon<OmsChargerNo> directChargeNoJson = chargerService.getChargerStatusNo("1", userCard);
		JsonCommon<OmsChargerNo> alternateChargeNoJson = chargerService.getChargerStatusNo("2",userCard);
		OmsChargerNo totalOmsChargerNo = new OmsChargerNo();
		totalOmsChargerNo.setCharge_no(directChargeNoJson.getPojo().getCharge_no() + alternateChargeNoJson.getPojo().getCharge_no());
		totalOmsChargerNo.setBespeak_no(directChargeNoJson.getPojo().getBespeak_no() + alternateChargeNoJson.getPojo().getBespeak_no());
		retJson.setPojo(totalOmsChargerNo);
		return retJson;
		
	}
	/**
	 * 查询所有站信息
	 * @param request null
	 * @return  station JsonForList<OmsStation>: 所有valid_flag =1的station站记录列表
	 * @modify	张金荣	
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JsonForList getMapDataPackage(GenericRecord request) throws Exception{
		OmsStation queryStation = new OmsStation();
		queryStation.setValid_flag(1);
		JsonForList<OmsStation> retJsons = stationService.getStationListWithIgnore(queryStation, null);
		List<OmsStation> lsStations = retJsons.getList();
		/*for(OmsStation station:lsStations){
			List<OmsStationLocation> lsStationLoc = this.omsStationLocationService.findValidByStationId(station.getStation_id());
			if(lsStationLoc!=null){
				station.setLocationList(lsStationLoc);
			}
			if(station.getDistrict_code()!=null){
				station.setProvince_code(station.getDistrict_code().substring(0,2)+"0000");
			}			
		}*/
		/*for(int i=0;i<lsStations.size();i++){
			List<OmsStationLocation> lsStationLoc = this.omsStationLocationService.findValidByStationId(lsStations.get(i).getStation_id());
			if(lsStationLoc!=null){
				lsStations.get(i).setLocationList(lsStationLoc);
			}
			if(StringUtil.isNotBlank(lsStations.get(i).getDistrict_code())){
				//省编码为区县编码的前两位+0000 构成
				lsStations.get(i).setProvince_code(lsStations.get(i).getDistrict_code().substring(0, 2)+"0000");
			}
		}*/
		ListIterator<OmsStation> iterator=lsStations.listIterator(lsStations.size());
		while(iterator.hasPrevious()){
			OmsStation omsStation = iterator.previous();
            List<OmsStationLocation> lsStationLoc = this.omsStationLocationService.findValidByStationId(omsStation.getStation_id());
			if(lsStationLoc.size()>0){
				omsStation.setLocationList(lsStationLoc);
				if(StringUtil.isNotBlank(omsStation.getDistrict_code())){
					//省编码为区县编码的前两位+0000 构成
					omsStation.setProvince_code(omsStation.getDistrict_code().substring(0, 2)+"0000");
				} 				
			}else {
				iterator.remove();
			}	
        }
		retJsons.setList(lsStations);
		return retJsons;
	}
	
	/**
	 * @param request {"reservationSn":"XXXX"} 预约流水号
	 * @return JsonCommon<OmsChargerBespeakBillRecord> :预约记录
	 * @throws Exception
	 */
	public JsonCommon getReservationDetailById(GenericRecord request) throws Exception {
		String reservationSn = request.get("reservationSn").toString();
		if(reservationSn==null||"".equals(reservationSn)){
			throw new Exception("call parameter error:reservationSn:"+reservationSn);
		}
		OmsChargerBespeakBillRecord queryBespeakBill = new OmsChargerBespeakBillRecord();
		queryBespeakBill.setBespeak_jrnl(reservationSn);
		JsonCommon<OmsChargerBespeakBillRecord> retJson = new JsonCommon<OmsChargerBespeakBillRecord>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		retJson.setPojo(billService.findBespeakBillOneExample(queryBespeakBill, null, null));
		return retJson;
	}
	/**
	 * 分页获取预约记录
	 * @param request {userCard:XXXX,pageNo:1} 用户卡号  页码（默认1）
	 * @return JsonForList<OmsChargerChargeBillRecord> 预约充电记录
	 */
	public JsonForList getReservationListByPage(GenericRecord request) throws Exception{
		String userCard = request.get("userCard").toString();
		int pageNo = (int)(request.get("pageNo")==null?1:request.get("pageNo"));
		if(userCard==null||"".equals(userCard)){
			throw new Exception("call parameter error:userCard:"+userCard);
		}
		
		OmsChargerBespeakBillRecord queryBespeakBill = new OmsChargerBespeakBillRecord();
		queryBespeakBill.setUser_pay_card(userCard);
		JsonForList<OmsChargerBespeakBillRecord> retJsons = new JsonForList<OmsChargerBespeakBillRecord>();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		retJsons.setList(billService.findBespeakBills(queryBespeakBill, pageNo));
		return retJsons;
	}
	
	
	/**
	 * @param request {"chargeSn":"充电序列号"}
	 * @return "OK"
	 * @throws Exception
	 */
	public JsonCommon<String> closeCharge(GenericRecord request) throws Exception {
		String chargeSn = request.get("chargeSn").toString();
		if(chargeSn==null||"".equals(chargeSn)){
			throw new Exception("call parameter error:chargeSn:"+chargeSn);
		}
		OmsChargerChargeBillRecord queryBill = new OmsChargerChargeBillRecord();
		queryBill.setCharge_jrnl(chargeSn);
		queryBill = this.billService.findOneChargeBillExample(queryBill, null,null);
		OmsCharger queryCharger = this.chargerService.findChargerDetailByChargerId(queryBill.getCharger_id());
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("chargerId", queryBill.getCharger_id());
		paramMap.put("userCard", queryBill.getUser_pay_card());
		paramMap.put("portNo", String.valueOf(queryBill.getPort()));
		paramMap.put("protocol_type", queryCharger.getProtocol_type());
		paramMap.put("protocol_version", queryCharger.getProtocol_version());
		//chargeStartSerialNumber
		paramMap.put("chargeStartSerialNumber", queryBill.getMsg_charge_jrnl());
		
		return this.omsChargeService.stopCharge(paramMap);
		
//		final Map map = paramMap;
//		
//		java.util.concurrent.Future<JsonCommon<String>> future = receiveExecutorService.submit(new Callable<JsonCommon<String>>() {
//
//			@SuppressWarnings("unchecked")
//			@Override
//			public JsonCommon<String> call() throws Exception {
//				return omsChargeService.stopCharge(map);
//			}
//		});
//		return future.get();
	}
	/**
	 * 开启充电接口
	 * @param request { "userCard": "string","chargerId": "string","chargerPortNo":"string"}
	 * @return JsonCommon<String> "OK"
	 * @throws Exception
	 */
	public JsonCommon<String> startCharge(GenericRecord request) throws Exception{
		String chargerId = request.get("chargerId").toString();
		String userCard =  request.get("userCard").toString();
		String portNo = request.get("chargerPortNo").toString();
		if(userCard==null||"".equals(userCard)||
				chargerId==null||"".equals(chargerId)||
				portNo==null||"".equals(portNo)){
			throw new Exception("call parameter error:userCard:"+userCard+" portNo:"+portNo+" chargeId:"+chargerId);
		}
		OmsCharger queryCharger = this.chargerService.findChargerDetailByChargerId(chargerId);
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("chargerId", chargerId);
		paramMap.put("userCard", userCard);
		paramMap.put("portNo", portNo);
		paramMap.put("protocol_type", queryCharger.getProtocol_type());
		paramMap.put("protocol_version", queryCharger.getProtocol_version());

		Integer charger_port_no = Integer.valueOf(portNo);

		boolean canCharge = false;
		log.debug(paramMap);

		if (queryCharger != null)
		{
			switch (queryCharger.getCharger_type())
			{//电桩充电类型
				case 1:  //直流
					OmsChargerStateDirect omsChargerStateDirect = new OmsChargerStateDirect();
					omsChargerStateDirect.setCharger_id(queryCharger.getCharger_id());
					omsChargerStateDirect.setPort_no(charger_port_no);
					omsChargerStateDirect = chargerService.findOneDirect(omsChargerStateDirect, null, null);//查找该桩现在的状态
					log.debug(omsChargerStateDirect.getCharge_status());
					switch (omsChargerStateDirect.getCharge_status())
					{
						case 0:  //空闲
							//直接进行充电
							canCharge = true;
							break;
						case 1: //预约：要查看是否是本人预约
							String qry_user_pay_card = chargerService.getChargerBespeakBill(queryCharger.getCharger_id(), charger_port_no, null).getUser_pay_card();
							if (userCard.equals(qry_user_pay_card))
							{
								//充电
								canCharge = true;
							}
							break;
					}
					break;
				case 2:     //交流
					OmsChargerStateAlternate omsChargerStateAlternate = new OmsChargerStateAlternate();
					omsChargerStateAlternate.setCharger_id(queryCharger.getCharger_id());
					omsChargerStateAlternate.setPort_no(charger_port_no);

					omsChargerStateAlternate = chargerService.findOneAlternate(omsChargerStateAlternate, null, null);//查找该桩现在的状态
					log.debug(omsChargerStateAlternate.getCharge_status());
					switch (omsChargerStateAlternate.getCharge_status())
					{
						case 0:  //空闲
							//直接进行充电
							canCharge = true;
							break;
						case 1: //预约：要查看是否是本人预约
							String qry_user_pay_card = chargerService.getChargerBespeakBill(queryCharger.getCharger_id(), charger_port_no, null).getUser_pay_card();
							if (userCard.equals(qry_user_pay_card))
							{
								//充电
								canCharge = true;
							}
							break;
					}
					break;
			}
		}

		JsonCommon<String> json = new JsonCommon();

		if (!canCharge)
		{
			json.setCode(MsgCodeEnum.ERROR403.getMsgCode());
			json.setMsg(MsgCodeEnum.ERROR403.getMsgInfo() + ":不是充电或者预约状态");
			log.debug(json.getMsg());
			if(queryCharger != null)
			{
				final String charger_id = new String(chargerId);
				receiveExecutorService.submit(new Runnable()
				{
					@Override
					public void run()
					{
						try
						{
							NotifyAppServer.exceptionNotify(AppServerConstant.EXCEPTION_NOTIFY_ACTION_CHARGE, "", charger_id, MsgCodeEnum.ERROR403.getMsgCode());
						}
						catch (BizException e)
						{
							log.error(e.getMessage(), e);
						}
					}
				});
			}
			return json;
		}

		//		return this.omsChargeService.startCharge(paramMap);

		final Map map = paramMap;

		java.util.concurrent.Future<MessageFuture> future = receiveExecutorService.submit(new Callable<MessageFuture>()
		{

			@SuppressWarnings("unchecked")
			@Override
			public MessageFuture call() throws Exception
			{
				MessageFuture f = omsChargeService.startCharge(map);
				return f;
			}
		});
		MessageFuture msgFuture = future.get();

		if (msgFuture != null)
		{
			if (msgFuture.await(maxWaitMillsec))
			{
				String msg = msgFuture.getMessage();
				final String serialNo = MessageAnalysisHelper.getSerialNoFromSendingMessage(msg, queryCharger.getCharger_id());
				final String charger_id = new String(chargerId);
				if (serialNo != null)
				{
					if (msgFuture.isSuccess())
					{
						json.setCode("200");
						json.setMsg("Success");
						log.debug(json.getMsg());
						NotifyAppServer.startChargeReturn(serialNo);
					}
					else
					{
						final String errorCode = msgFuture.getErrorCode();
						json.setCode(msgFuture.getErrorCode());
						json.setMsg(msgFuture.getErrorMessage());
						log.debug(json.getCode());
						receiveExecutorService.submit(new Runnable()
						{
							@Override
							public void run()
							{
								try
								{
									NotifyAppServer.exceptionNotify(AppServerConstant.EXCEPTION_NOTIFY_ACTION_CHARGE, serialNo, charger_id, errorCode);
								}
								catch (BizException e)
								{
									log.error(e.getMessage(), e);
								}
							}
						});

					}
				}
			}
			else
			{
				json.setCode("400");
				json.setMsg("Time-out");
				log.debug(json.getMsg());
			}

		}

		return json;
	}
	
	/**
	 * 提交站点报错信息
	 * @param request {stationId:"站Id",errorType:"报错类型"}
	 * @return JsonCommon<OmsStationCorrectList> 报错信息
	 * @throws Exception
	 */
	public JsonCommon<OmsStationCorrectList> stationErrorInfo(GenericRecord request) throws Exception{
		String stationId = request.get("stationId").toString();
		String errorType =  request.get("errorType").toString();
		String userTelephone =  request.get("userTelephone").toString();
		if(stationId==null||"".equals(stationId)||
				errorType==null||"".equals(errorType)||
						userTelephone==null||"".equals(userTelephone)){
			throw new Exception("call parameter error: stationId:"+stationId+" errorType:"+errorType+" userTelephone:"+userTelephone);
		}
		OmsStationCorrectList stationCorrectList = new OmsStationCorrectList();
		stationCorrectList.setStation_id(stationId);
		stationCorrectList.setError_type_id(Integer.parseInt(errorType));
		stationCorrectList.setUser_telephone(userTelephone);
		stationCorrectList.setCreate_time(new Date());
		return  (JsonCommon<OmsStationCorrectList>) this.stationCorrectListService.add(stationCorrectList);
	}
	
	
	/**
	 * 取消预约
	 * @param request {"reservationSn":"XXXX"} 取消流水号
	 * @return JsonCommon<String> "OK"
	 * @throws Exception
	 */
	public JsonCommon<String> cancelReservation(GenericRecord request) throws Exception{
		String reservationSn = request.get("reservationSn").toString();
		if(reservationSn==null||"".equals(reservationSn)){
			throw new Exception("call parameter error:reservationSn:"+reservationSn);
		}
		OmsChargerBespeakBillRecord queryBespeakBill = new OmsChargerBespeakBillRecord();
		queryBespeakBill.setBespeak_jrnl(reservationSn);
		queryBespeakBill = this.billService.findBespeakBillOneExample(queryBespeakBill, null, null);
		OmsCharger queryCharger = this.chargerService.findChargerDetailByChargerId(queryBespeakBill.getCharger_id());
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("protocol_type",queryCharger.getProtocol_type());
		paramMap.put("protocol_version", queryCharger.getProtocol_version());
		paramMap.put("chargerId", queryBespeakBill.getCharger_id());
		paramMap.put("userCard", queryBespeakBill.getUser_pay_card());
		paramMap.put("portNo", String.valueOf(queryBespeakBill.getPort_no()));
		paramMap.put("bespeakStartSerialNumber", queryBespeakBill.getOms_msg_bespeak_jrnl());
		
//		return omsBespeakService.cancelBespeak(paramMap);
		
		final Map map = paramMap;

		log.info(receiveExecutorService.isShutdown());
		log.info(receiveExecutorService.isTerminated());
		log.info("Cancel reservation");
		java.util.concurrent.Future<JsonCommon<String>> future = receiveExecutorService.submit(new Callable<JsonCommon<String>>() {

			@Override
			public JsonCommon<String> call() throws Exception {
				log.info("Begin cancel reservation");
				return omsBespeakService.cancelBespeak(map);
			}
		});
		log.info("after thread");
		JsonCommon<String> json = future.get();
		log.info(json);
		return json;
	}
	
	
	/**
	 * 获取预约折扣信息
	 * @param request userCard:"用户卡号，20位",chargerId:"电桩地址",bespeak_minute:"预约开始时间（年月日时分秒）",bespeak_startTime:"预估预约时间（分钟数）",portNo:"端口号"
	 * @return JsonCommon<RetVo> 预约折扣信息
	 * @throws Exception 
	 */
	public JsonCommon getReservationDiscount(GenericRecord request) throws Exception{
		String userCard = request.get("userCard").toString();
		String portNo =  request.get("portNo").toString();
		String chargerId =  request.get("chargerId").toString();
		String bespeak_minute =  request.get("bespeakMinute").toString();
		String bespeak_startTime =  request.get("bespeakStartTime").toString();
		if(userCard==null||"".equals(userCard)||chargerId==null||"".equals(chargerId)
				||portNo==null||"".equals(portNo)||bespeak_minute==null
				||"".equals(bespeak_minute)||bespeak_startTime==null||"".equals(bespeak_startTime)
				){
			throw new Exception("call parameter error: userCard:"+userCard+" portNo:"+portNo
					           +" chargerId:"+chargerId+" bespeak_minute:"+bespeak_minute+
					           " bespeak_startTime:"+bespeak_startTime);
		}
		OrderBaseData orderBaseDataReserveationDiscount = new OrderBaseData();
		Date bespeak_startDt = this.dateFormat.parse(bespeak_startTime);
		Date bespeak_endDt = new Date(bespeak_startDt.getTime() + Integer.parseInt(bespeak_minute)*60*1000);

		OmsCharger queryCharger = this.chargerService.findChargerDetailByChargerId(chargerId);
		queryCharger.getRate_schema_bespeak_fee();
		List<OrderBaseData> queryList = new ArrayList<OrderBaseData>();
		orderBaseDataReserveationDiscount.setStartTime(bespeak_startDt);
		orderBaseDataReserveationDiscount.setEndTime(bespeak_endDt);
		orderBaseDataReserveationDiscount.setCardNo(userCard);
		orderBaseDataReserveationDiscount.setEquipmentNo(chargerId);
		orderBaseDataReserveationDiscount.setPlantId(queryCharger.getStation_id());
		orderBaseDataReserveationDiscount.setServiceNo(OrderServiceEnum.Reservation.value());
		orderBaseDataReserveationDiscount.setServiceProviderCode(queryCharger.getOper_merchant_id());
		orderBaseDataReserveationDiscount.setMerchantCode(queryCharger.getFee_oper_merchant_id());
		orderBaseDataReserveationDiscount.setIsCost(0);
		orderBaseDataReserveationDiscount.setAuxEquipmentNo("0");
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseDataReserveationDiscount.setAppId(BizSystemCode.DzApp.value());
		}
		BigDecimal a1=new BigDecimal(0.8); 
		BigDecimal a2=new BigDecimal(15);
		orderBaseDataReserveationDiscount.setUnitPrice(a1.divide(a2,0,BigDecimal.ROUND_HALF_EVEN));
		
				
		queryList.add(orderBaseDataReserveationDiscount);
		JsonCommon<RetVO> retJson = new JsonCommon<RetVO>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
//		RetVO retVO = orderRpcClient.servicePriceQuery(queryList);
		RetVO retVO = null;
		final List<OrderBaseData> map = queryList;
		java.util.concurrent.Future<RetVO> future = null;
		try {
			future = receiveExecutorService
					.submit(new Callable<RetVO>() {

						@SuppressWarnings("unchecked")
						@Override
						public RetVO call() throws Exception {
							//return orderRpcClient.servicePriceQuery(map);
							return null;
						}
					});
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			throw e;
		}
		retVO = future.get();
		if (retVO != null && retVO.getRetCode().equals(retVO.SuccessCode)){
			retJson.setPojo(retVO);		    
		} else{
			retJson.setCode(MsgCodeEnum.GET_RESERVATION_DISCOUNT_ERROR.getMsgCode());
			retJson.setMsg("getReservationDiscount fail");		     
		}
		return retJson;
	}
	
	
	/**
	 * 充电预约
	 * @param request {"userCard":"XXX","chargerId":"XXX","portNo":"01"} "用户卡号","电桩ID（桩地址）","电口"
	 * @return JsonCommon<String> "OK"
	 */
	public JsonCommon<String> chargeReservation(GenericRecord request) throws Exception{
		String chargerId = request.get("chargerId").toString();
		String userCard = request.get("userCard").toString();
		String portNo = request.get("portNo").toString();
		if(chargerId==null||"".equals(chargerId)||userCard==null||"".equals(userCard)){
			throw new Exception("call parameter error chargerId:"+chargerId + "userCard:"+userCard);
		}
		OmsCharger queryCharger = this.chargerService.findChargerDetailByChargerId(chargerId);
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("chargerId", chargerId);
		paramMap.put("userCard", userCard);
		paramMap.put("portNo", portNo);
		paramMap.put("protocol_type", queryCharger.getProtocol_type());
		paramMap.put("protocol_version", queryCharger.getProtocol_version());
		
//		return this.omsBespeakService.bespeak(paramMap);
		final Map map = paramMap;

		try {
			java.util.concurrent.Future<JsonCommon<String>> future = receiveExecutorService
					.submit(new Callable<JsonCommon<String>>() {

						@SuppressWarnings("unchecked")
						@Override
						public JsonCommon<String> call() throws Exception {
							return omsBespeakService.bespeak(map);
						}
					});
			return future.get();
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			throw e;
		}
	}
	
	
	/**
	 * 电桩图片上传
	 * @param request {"chargerId":"XXX","images":byte[]} 电桩id, 位数组
	 * @return JsonCommon<String> "OK"
	 * @throws Exception
	 */
//	public JsonCommon uploadImage (GenericRecord request)throws Exception{
//		String chargerId = request.get("chargerId").toString();
//		ByteBuffer receiveImageBytes = (ByteBuffer)request.get("images");
//		if(chargerId==null||"".equals(chargerId)||receiveImageBytes==null){
//			throw new Exception("call parameter chargerId:"+chargerId + "images:"+receiveImageBytes);
//		}	
//		//0:find charger by chargerid
//		OmsCharger queryCharger = this.chargerService.findChargerDetailByChargerId(chargerId);
//		//1:find station by stationId
//		OmsStationCollect targetStation = (OmsStationCollect)this.stationCollectService.findById(queryCharger.getStation_id()).getPojo();
//		if(targetStation!=null){
//			//2:write image bytes to file
//			String imageFilePath = uploadImagePath+File.separator+chargerId+"_"+System.currentTimeMillis()+".jpg";
//			FileChannel fc = new FileOutputStream(imageFilePath).getChannel();
//			fc.write(receiveImageBytes);
//			fc.close();
//			//3:update oms_station_collection record
//			String orginalPhotoPath = targetStation.getPhoto();
//			targetStation.setPhoto(orginalPhotoPath==null?imageFilePath:orginalPhotoPath+","+orginalPhotoPath);
//		}
//		return new JsonCommon<String>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
//	}
	
	/**
	 * 分页获取站点使用的人列表
	 * @param request {"station_id":"站ID","pageNo":"页码"}
	 * @return JsonForList<String> userCard列表
	 * @throws Exception 
	 */
	public JsonForList getUsedUserIdByStationId(GenericRecord request) throws Exception{
		String stationId = request.get("stationId").toString();
		int pageNo = (int)(request.get("pageNo")==null?1:request.get("pageNo"));
		if(stationId==null||"".equals(stationId)){
			throw new Exception("call parameter error:stationId:"+stationId);
		}
		String sql = "select distinct user_pay_card from oms_charger_charge_bill_record where " +
				     "station_id = '"+stationId + "' LIMIT  " + pageNo*15 + "  , 15";
		List<Map<String,Object>> ListUserCardMap = this.billService.findMapDatabySql(sql);
		List<String> userCards = new ArrayList<String>();
		for(Map<String,Object> userCardMap :ListUserCardMap){
			userCards.add((String)userCardMap.get("user_pay_card"));
		}
		JsonForList<String> retJsons = new JsonForList<String>();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		retJsons.setList(userCards);
		return retJsons;
	}
	

	/**
	 * 获取电桩详细信息
	 * @param request {"chargerId":"桩Id"}
	 * @return JsonCommon<OmsCharge> 桩信息
	 * @throws Exception 
	 */
	public JsonCommon getChargerDetailByChargerId(GenericRecord request) throws Exception{
		String charger_id = request.get("chargerId").toString();
		if(charger_id==null||"".equals(charger_id)){
			throw new Exception("call parameter charger_id:"+charger_id );
		}	
		JsonCommon<OmsCharger> retJson = new JsonCommon<OmsCharger>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		OmsCharger retCharger = this.chargerService.findChargerDetailByChargerId(charger_id);
		if (retCharger != null) {
			retCharger.setDeviceType(this.deviceTypeService.findExampleByDeviceId(retCharger.getDevice_id()));
		}
		retJson.setPojo(retCharger);
		return retJson;
	}
	
	
	/**
	 * 通过二维码获取电桩详细信息
	 * @param request {"qrCode":"桩二维码"}
	 * @return JsonCommon<OmsCharge> 桩信息
	 * @throws Exception 
	 */
	public JsonCommon getChargerDetailByQrCode(GenericRecord request) throws Exception{
		String qr_code = request.get("qrCode").toString();
		if(qr_code==null||"".equals(qr_code)){
			throw new Exception("call parameter qr_code:"+qr_code );
		}	
		JsonCommon<OmsCharger> retJson = new JsonCommon<OmsCharger>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		OmsCharger retCharger = this.chargerService.findChargerDetailByQrCode(qr_code);
		if (retCharger != null) {
			retJson.setCode("200");
			retJson.setMsg("success");
			retCharger.setDeviceType(this.deviceTypeService.findExampleByDeviceId(retCharger.getDevice_id()));
			retJson.setPojo(retCharger);
		} else {
			retJson.setCode(OmsConstant.ErrorCodeEnum.ChargerQueryNull.value());
			retJson.setMsg(OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc());
		}
		return retJson;
	}
	
	/**
	 * 查询电站详细信息
	 * @param request {"stationId":"电站Id"}
	 * @return JsonCommon<OmsStation> 站信息
	 * @throws Exception
	 */
	public JsonCommon getStationDetailByStationId(GenericRecord request) throws Exception{
		String stationId = request.get("stationId").toString();
		if(stationId==null||"".equals(stationId)){
			throw new Exception("call parameter error stationId:"+stationId );
		}
		JsonCommon<OmsStationAll> retJson = new JsonCommon<>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		OmsStationAll retStaton = this.stationService.getStationAllById(stationId);
//		
//		JsonCommon<OmsStation> retJson = new JsonCommon<>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
//		OmsStation retStaton = this.stationService.getStationById(stationId);
		List<OmsStationLocation> lsStationLoc = this.omsStationLocationService.findValidByStationId(retStaton.getStation_id());
		retStaton.setLocationList(lsStationLoc);
		//同时获取该站点在七牛云服务的图片名称:多个以逗号分隔，具体路径由APP自己处理
		String remoteFileNames = qiniuService.getRemoteFileNames("oms_station", retStaton.getStation_id());
		retStaton.setPhoto(remoteFileNames);
		//pengyu add 20160624
		OmsOperMerchant omsOperMerchant_query = new OmsOperMerchant();
		if(StringUtil.isNotBlank(retStaton.getOper_merchant_id())){
			omsOperMerchant_query.setOper_merchant_id(retStaton.getOper_merchant_id());
			OmsOperMerchant omsOperMerchant = omsOperMerchantDao.findOneExample(omsOperMerchant_query, null, null);
			if(omsOperMerchant != null){
				retStaton.setOper_name(omsOperMerchant.getOper_name());
			}
		}
		retJson.setPojo(retStaton);
		return retJson;
	}
	
	/**
	 * 获取站点下面的电桩列表
	 * @param request {"stationId":"电站Id"}
	 * @return JsonForList<OmsCharger> 电桩信息
	 * @throws Exception 
	 * @modify 张金荣
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JsonForList getChargerListByStationId(GenericRecord request) throws Exception{
		String station_id = request.get("stationId").toString();
		if(station_id==null||"".equals(station_id)){
			throw new Exception("call parameter error  station_id:"+station_id );
		}
		OmsCharger queryCharger = new OmsCharger();
		queryCharger.setStation_id(station_id);
		queryCharger.setValid_flag(1);//只查询有效桩
		JsonForList<OmsCharger> retJsons = this.chargerService.getChargerListByStation(queryCharger);
		for(int i=0;i<retJsons.getList().size();i++){
			retJsons.getList().get(i).setDeviceType(this.deviceTypeService.findExampleByDeviceId(retJsons.getList().get(i).getDevice_id()));
		}
		return retJsons;
	}
	/**
	 * 获取站点下的空闲桩列表
	 * @param request {"stationId":"站Id"}
	 * @return JsonCommon<Map<String,Long>> 站下空闲桩数量(不包括有电口在充电的桩)
	 * Map<String,Long>: {free_Chargers_count_direct:直流桩数量 ，free_Chargers_count_alter:交流桩数量}
	 */
	public JsonCommon getFreeChargerByStationId(GenericRecord request) throws Exception{
		String station_id = request.get("stationId").toString();
		if(station_id==null||"".equals(station_id)){
			throw new Exception("call parameter error  station_id:"+station_id );
		}
		JsonCommon<Map<String,Long>> retJson = new JsonCommon<Map<String,Long>>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		Map<String,Long> retMap = new HashMap<String,Long>();
		retMap.put("free_Chargers_count_alter", this.chargerService.getFreeChargerByStationId(station_id, 2));
		retMap.put("free_Chargers_count_direct", this.chargerService.getFreeChargerByStationId(station_id, 1));
		retJson.setPojo(retMap);
		return retJson;
	}
	
	/**
	 * 获取错误类型列表
	 * @param request N/A
	 * @return JsonForList<OmsErrorType> 所有报错类型列表
	 */
	public JsonForList getErrorCode(GenericRecord request){
		return this.errorTypeService.findAll();		
	}
	
	/**
	 * 通过充电ID获取充电记录详细
	 * @param request {"chargeSn":"XXXX"} 充电流水号
	 * @return JsonCommon<OmsChargerChargeBillRecord> :充电详细信息
	 */
	public JsonCommon<OmsChargerChargeBillRecord> getChargeDetailById (GenericRecord request) throws Exception {
		Object chargeSnObj = request.get("chargeSn");
		String chargeSn = (chargeSnObj.toString());
		if(chargeSn==null||"".equals(chargeSn)){
			throw new Exception("call parameter error chargeSn:"+chargeSn);
		}
		OmsChargerChargeBillRecord queryChargerChargeBill = new OmsChargerChargeBillRecord();
		queryChargerChargeBill.setCharge_jrnl(chargeSn);
		JsonCommon<OmsChargerChargeBillRecord> retJson = new JsonCommon<OmsChargerChargeBillRecord>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		
		retJson.setPojo(this.billService.findOneChargeBillExample(queryChargerChargeBill, null, null));
		return retJson;
	}
	

	/**
	 * @param request {"userCard":"XXXXX","pageNo":1} 用户卡号  ,页码（默认1）
	 * @return JsonForList<OmsChargerChargeBillRecord> :充电记录列表
	 * @throws Exception
	 */
	public JsonForList getChargeListByPage(GenericRecord request) throws Exception {
		String userCard = (request.get("userCard").toString());
		int pageNo = (int)(request.get("pageNo")==null?1:request.get("pageNo"));
		if(userCard==null||"".equals(userCard)){
			throw new Exception("call parameter error:userCard:"+userCard);
		}		
		OmsChargerChargeBillRecord queryChargeBill = new OmsChargerChargeBillRecord();
		queryChargeBill.setUser_pay_card(userCard);
		JsonForList<OmsChargerChargeBillRecord> retJsons = new JsonForList<OmsChargerChargeBillRecord>();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		retJsons.setList(this.billService.findChargeBillsWithCondition(queryChargeBill, " where user_pay_card = '" + userCard + "'", pageNo));
		return retJsons;
	}
	
	/**
	 * @param request {"charger_id":桩id}
	 * @return JsonForList<OmsCharger> 
	 * @throws Exception
	 */
	public JsonForList getChargerPortsByChargerId(GenericRecord request) throws Exception {
		String charger_id = request.get("chargerId").toString();
		if(charger_id==null||"".equals(charger_id)){
			throw new Exception("call parameter error: charger_id:"+charger_id);
		}
		JsonForList retJsons = new JsonForList();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		retJsons.setList(this.chargerService.getPortsStateInfo(charger_id));
		return retJsons;
		
	}
	
	/**
	 * 查询抢头状态
	 * @param request {"chargerId": 桩Id "chargerPort" :电口Id
	 * @return 
	 * @throws Exception
	 */
	public JsonCommon getChargerPortStatus(GenericRecord request) throws Exception
	{
		String charger_id = request.get("chargerId").toString();
		String charger_port_no = request.get("chargerPort").toString();
		log.info("getPortStateInfo chargerId:" + charger_id + " port_no:" + charger_port_no);
		if (StringUtils.isEmpty(charger_id) || StringUtils.isEmpty(charger_port_no))
		{
			throw new Exception("call parameter error: charger_id:" + charger_id + " charger_port_no:" + charger_port_no);
		}

		return chargerService.getPortStateInfo(charger_id, charger_port_no);

	}
	
	/**
	 * 查询七牛云UpToken
	 * @param
	 * @return JsonCommon<String> "OK"
	 */
	public JsonCommon<String> getQiniuyunUpToken(GenericRecord request) throws Exception{
		JsonCommon<String> json = new JsonCommon<String>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		json.setPojo(this.qiniuService.getUpToken());
		return json;
	}
	
	
	/**
	 * 通过桩ID、枪口ID查询当前枪口状态对应的流水号（预约、充电）、枪口状态、用户卡号
	 * @param request { "chargerId": "string","chargerPort": "string"}
	 * @return JsonCommon<String> "OK"
	 */
	public JsonCommon<String> getIdOfNowStatusByChargeridAndPortid(GenericRecord request) throws Exception{
		String charger_id = request.get("chargerId").toString();
		Integer charger_port_no = Integer.parseInt(request.get("chargerPort").toString());
		if(charger_id==null||"".equals(charger_id)||charger_port_no==null||"".equals(charger_port_no)){
			throw new Exception("call parameter error: charger_id:"+charger_id+" charger_port_no:"+charger_port_no);
		}
		
		String  jrnl = null;
		JsonCommon<String> json = new JsonCommon<String>(MsgCodeEnum.SUCCESS.getMsgCode(),MsgCodeEnum.SUCCESS.getMsgInfo());
		OmsCharger charger;
		List<OmsCharger> list = chargerService.getChargerByIds(charger_id);
        if (list.size()>0) {
        	charger = list.get(0);
        	switch (charger.getCharger_type()) {//充电桩状态
    		case 1://直流
    			OmsChargerStateDirect omsChargerStateDirect = new OmsChargerStateDirect();
    			omsChargerStateDirect.setCharger_id(charger_id);
    			omsChargerStateDirect.setPort_no(charger_port_no);
    			omsChargerStateDirect = chargerService.findOneDirect(omsChargerStateDirect, null, null);
    			
    			switch (omsChargerStateDirect.getCharge_status()) {
				case 1:  //预约
					jrnl = chargerService.getChargerBespeakBill(charger_id,charger_port_no,omsChargerStateDirect.getUser_pay_card()).getBespeak_jrnl() ;
					break;
                case 2: //充电
                	jrnl = chargerService.getChargerChargeBill(charger_id,charger_port_no,omsChargerStateDirect.getUser_pay_card()).getCharge_jrnl();
					break;
				default:
					//不是充电或者预约状态
					json = new JsonCommon<String>(MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgCode(),MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgInfo()+":该桩不是充电或者预约状态");
					break;
				}
    		case 2:	//交流
    			OmsChargerStateAlternate omsChargerStateAlternate = new OmsChargerStateAlternate();
    			omsChargerStateAlternate.setCharger_id(charger_id);
    			omsChargerStateAlternate.setPort_no(charger_port_no);
    			
    			omsChargerStateAlternate  = chargerService.findOneAlternate(omsChargerStateAlternate, null, null);
    			switch (omsChargerStateAlternate.getCharge_status()) {
				case 1:  //预约
					jrnl = chargerService.getChargerBespeakBill(charger_id,charger_port_no,omsChargerStateAlternate.getUser_pay_card()).getBespeak_jrnl() ;
					break;
                case 2: //充电
                	jrnl = chargerService.getChargerChargeBill(charger_id,charger_port_no,omsChargerStateAlternate.getUser_pay_card()).getCharge_jrnl();
					break;
				default:
					//不是充电或者预约状态
					json = new JsonCommon<String>(MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgCode(),MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgInfo()+":该桩不是充电或者预约状态");
					break;
				}
    			break;

    		default:
    			//桩charger_type异常，不是交流桩或者直流桩
    			break;
    		}
		}else{
			//没有找到电桩
			json = new JsonCommon<String>(MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgCode(),MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgInfo()+":通过此桩号，没有查询到桩");
		}
        if (jrnl!=null) {
            json.setPojo(jrnl);			
		}
		return json;
	}

	/**
	 * 二维码开启充电
	 * @param request { "qrCode": "string","userPayCard": "string","chargerPortNo":"string"}
	 * @return JsonCommon<String> "OK"
	 * @throws Exception
	 */
	public JsonCommon<String> startChargeByQrCode(GenericRecord request) throws Exception{
		String qr_code = request.get("qrCode").toString();
		String user_pay_card = request.get("userPayCard").toString();
		Integer charger_port_no = Integer.parseInt(request.get("chargerPortNo").toString());
		if(qr_code==null||"".equals(qr_code)||user_pay_card==null||"".equals(user_pay_card)||charger_port_no==null||"".equals(charger_port_no)){
			throw new Exception("call parameter error: qr_en ,code:" + qr_code + " user_pay_card:" + user_pay_card + " charger_port_no:" + charger_port_no);
		}

		OmsCharger charger = new OmsCharger();
		charger.setQr_code(qr_code);
		OmsCharger queryCharger = chargerService.findOneExample(charger, null,null);//通过二维码找到该桩的详细信息
		
		boolean  canCharge = false;
		JsonCommon<String> json = new JsonCommon<String>();
		log.debug(qr_code);
		if (queryCharger == null) { //未找到充电桩
			json = new JsonCommon<String>(MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgCode(),MsgCodeEnum.CHARGER_QUERY_ERROR.getMsgInfo());
		}else {
			switch (queryCharger.getCharger_type()) {//电桩充电类型
			case 1:  //直流
				OmsChargerStateDirect omsChargerStateDirect = new OmsChargerStateDirect();
				omsChargerStateDirect.setCharger_id(queryCharger.getCharger_id());
				omsChargerStateDirect.setPort_no(charger_port_no);
				omsChargerStateDirect = chargerService.findOneDirect(omsChargerStateDirect, null, null);//查找该桩现在的状态
				log.debug(omsChargerStateDirect.getCharge_status());
				switch (omsChargerStateDirect.getCharge_status()) {
					case 0:  //空闲
						//直接进行充电
						canCharge = true;
						break;
		            case 1: //预约：要查看是否是本人预约
		            	String  qry_user_pay_card= chargerService.getChargerBespeakBill(queryCharger.getCharger_id(),charger_port_no,null).getUser_pay_card();
		            	if (user_pay_card.equals(qry_user_pay_card)) {
						    //充电
		            		canCharge = true;	
						}else {
							//已经被其他人预约：不能充电
							json = new JsonCommon<String>(MsgCodeEnum.ERROR403.getMsgCode(),MsgCodeEnum.ERROR403.getMsgInfo()+":已经被其他人预约");
						}
						break;
					default:
						//不是充电或者预约状态：不能充电
						json = new JsonCommon<String>(MsgCodeEnum.ERROR403.getMsgCode(),MsgCodeEnum.ERROR403.getMsgInfo()+":不是充电或者预约状态");
						break;
				}
			case 2:	 //交流
				OmsChargerStateAlternate omsChargerStateAlternate = new OmsChargerStateAlternate();
				omsChargerStateAlternate.setCharger_id(queryCharger.getCharger_id());
				omsChargerStateAlternate.setPort_no(charger_port_no);

				omsChargerStateAlternate  = chargerService.findOneAlternate(omsChargerStateAlternate, null, null);//查找该桩现在的状态
				log.debug(omsChargerStateAlternate.getCharge_status());
				switch (omsChargerStateAlternate.getCharge_status()) {
					case 0:  //空闲
						//直接进行充电
						canCharge = true;
						break;
		            case 1: //预约：要查看是否是本人预约
		            	String  qry_user_pay_card= chargerService.getChargerBespeakBill(queryCharger.getCharger_id(),charger_port_no,null).getUser_pay_card();
		            	if (user_pay_card.equals(qry_user_pay_card)) {
							//充电
		            		canCharge = true;
						}else {
							//已经被其他人预约：不能充电
							json = new JsonCommon<String>(MsgCodeEnum.ERROR403.getMsgCode(),MsgCodeEnum.ERROR403.getMsgInfo()+":已经被其他人预约");
						}
						break;
					default:
						//不是充电或者预约状态：不能充电
						json = new JsonCommon<String>(MsgCodeEnum.ERROR403.getMsgCode(),MsgCodeEnum.ERROR403.getMsgInfo()+":不是充电或者预约状态");
						break;
				}
				break;

			default:
				//桩charger_type异常，不是交流桩或者直流桩
				break;
			}	
		}
		log.debug(canCharge);

		if (!canCharge)
		{
			json.setCode(MsgCodeEnum.ERROR403.getMsgCode());
			json.setMsg(MsgCodeEnum.ERROR403.getMsgInfo() + ":不是充电或者预约状态");
			log.debug(json.getMsg());
			if(queryCharger != null)
			{
				final String charger_id = new String(queryCharger.getCharger_id());
				receiveExecutorService.submit(new Runnable()
				{
					@Override
					public void run()
					{
						try
						{
							NotifyAppServer.exceptionNotify(AppServerConstant.EXCEPTION_NOTIFY_ACTION_CHARGE, "", charger_id, MsgCodeEnum.ERROR403.getMsgCode());
						}
						catch (BizException e)
						{
							log.error(e.getMessage(), e);
						}
					}
				});
			}
			return json;
		}
				
		else {
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("chargerId", queryCharger.getCard_gprs());
			paramMap.put("userCard", user_pay_card);
			paramMap.put("portNo", charger_port_no.toString());
			paramMap.put("protocol_type", queryCharger.getProtocol_type());
			paramMap.put("protocol_version", queryCharger.getProtocol_version());

			final Map map = paramMap;		
			java.util.concurrent.Future<MessageFuture> future = receiveExecutorService.submit(new Callable<MessageFuture>() {
				@SuppressWarnings("unchecked")
				@Override
				public MessageFuture call() throws Exception {
					return omsChargeService.startCharge(map);
				}
			});

			MessageFuture msgFuture = future.get();
			if(msgFuture != null)
			{
				if(msgFuture.await(maxWaitMillsec))
				{
					String msg = msgFuture.getMessage();
					String serialNo = MessageAnalysisHelper.getSerialNoFromSendingMessage(msg, queryCharger.getCharger_id());
					if(serialNo != null)
					{
						if (msgFuture.isSuccess())
							NotifyAppServer.startChargeReturn(serialNo);

					}
				}
			}
		}	
				
		return json;
	}
	
	
	/**
	 * 通过用户卡号，查询当前用户正在使用的预约、充电信息
	 * @param  request { "userPayCard": "string"}   用户卡号
	 * @return JsonCommon 预约、充电信息
	 */
	public JsonCommon getChargeInfoAndBespeakInfoByUserPayCard(GenericRecord request) throws Exception{
		String user_pay_card = request.get("userPayCard").toString();
		if(user_pay_card==null||"".equals(user_pay_card)){
			throw new Exception("call parameter error: user_pay_card:" + user_pay_card);
		}
		
		JsonCommon retJsons = chargerService.getChargeInfoAndBespeakInfoByUserPayCard(user_pay_card);	
		return retJsons;
	}
	
	/**
	 * 通过订单号，查询该订单详细预约信息、电桩信息、电站信息
	 * @param  request { "orderNo": "string"}   订单号
	 * @return JsonCommon   详细预约信息、电桩信息、电站信息
	 */
	public JsonCommon getBespeakDetailInfoByOrderNo(GenericRecord request) throws Exception{
		String order_no = request.get("orderNo").toString();
		if(order_no==null||"".equals(order_no)){
			throw new Exception("call parameter error: order_no:" + order_no);
		}
		
		JsonCommon retJsons = chargerService.getBespeakDetailInfoByOrderNo(order_no);	
		return retJsons;
	}
	
	/**
	 * 通过订单号，查询该订单详细充电信息、电桩信息、电站信息
	 * @param  request { "orderNo": "string"}   订单号
	 * @return JsonCommon  详细充电信息、电桩信息、电站信息
	 */
	public JsonCommon getChargeDetailInfoByOrderNo(GenericRecord request) throws Exception{
		String order_no = request.get("orderNo").toString();
		if(order_no==null||"".equals(order_no)){
			throw new Exception("call parameter error: order_no:" + order_no);
		}
		
		JsonCommon retJsons = chargerService.getChargeDetailInfoByOrderNo(order_no);	
		return retJsons;
	}

	/**
	 * 通过桩号，查询该桩的当前时间的费率信息
	 * @param request {"chargerId":"桩Id"}
	 * @return JsonCommon list<OmsChargerRate> 费率信息
	 * @throws Exception 
	 */
	public JsonForList getChargerRate(GenericRecord request) throws Exception{
		String charger_id = request.get("chargerId").toString();
		if(charger_id==null||"".equals(charger_id)){
			throw new Exception("call parameter error:charger_id:"+charger_id );
		}	

		JsonForList<OmsChargerRate> retJsons = new JsonForList<OmsChargerRate>();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		List<OmsChargerRate> retRate = chargerService.findChargerRateByChargerId(charger_id);

		retJsons.setList(retRate);
		return retJsons;
	}
	
	/**
	 * 删除七牛云上的图片
	 * @param request {"imageNames":"图片名称，多个以逗号分隔"}
	 * @return JsonCommon<String> "OK"
	 */
	public JsonForList deleteQiniuyunImage(GenericRecord request) throws Exception{
		String imageNames = request.get("imageNames").toString();
		if(imageNames==null||"".equals(imageNames)){
			throw new Exception("call parameter error:imageNames:"+imageNames );
		}	
		
		//删除结果集：返回前端
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		String[]  list =  imageNames.split(",");
		if(list.length>0){
			for(String imageName :list){
				if (qiniuService.delete(imageName)) {			
					Map map = new HashMap<String, Object>();  
					map.put("filename", imageName);
					map.put("deleteResult", "200");
					resultList.add(map);
				}else {
					Map map = new HashMap<String, Object>();  
					map.put("filename", imageName);
					map.put("deleteResult", "七牛云删除失败!");
					resultList.add(map);
				}
			}
		}
		
		JsonForList retJsons = new JsonForList();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		retJsons.setList(resultList);
		return retJsons;
	}
	
	/**
	 * 查询所有外部站点信息
	 * @param request {"province_code": "省代码"}
	 * @return  station JsonForList<OmsStationExternal>
	 */
	@SuppressWarnings("unchecked")
	public JsonForList getExternalStation(GenericRecord request) throws Exception {
		String province_code = request.get("provinceCode").toString();
		
		JsonForList<OmsStationExternal> retJsons = new JsonForList<OmsStationExternal>();
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		OmsStationExternal queryStationExt = new OmsStationExternal();
		queryStationExt.setValid_flag(1);
		
		if(province_code==null||"".equals(province_code)){
			retJsons = stationExtenrnalService.getStationList(queryStationExt);
		}else{
			List<OmsStationExternal> lsStationExt = stationExtenrnalService.getStationByProvinceCode(province_code);
			retJsons.setList(lsStationExt);
		}
		
		List<OmsStationExternal> lsStations = retJsons.getList();
		ListIterator<OmsStationExternal> iterator = lsStations.listIterator(lsStations.size());
		while(iterator.hasPrevious()){
			OmsStationExternal omsStationExt = iterator.previous();
            List<OmsStationLocation> lsStationLoc = this.omsStationLocationService.findValidByStationId(omsStationExt.getStation_id());
            if(lsStationLoc.size()>0){
            	omsStationExt.setLocationList(lsStationLoc);
            	if(StringUtil.isNotBlank(omsStationExt.getDistrict_code())){
					//省编码为区县编码的前两位+0000 构成
					omsStationExt.setProvince_code(omsStationExt.getDistrict_code().substring(0, 2)+"0000");
				}
            }else{
            	iterator.remove();
            }
		}
		
		retJsons.setList(lsStations);
		return retJsons;
	}


	/**
	 * 根据坐标查询站点
	 */
	public JsonForList getStationsByCoord(GenericRecord request) throws Exception
	{
		String x = request.get("x").toString();
		String y = request.get("y").toString();
		String distance = request.get("distance").toString();

		JsonForList<OmsStation> retJsons = new JsonForList<>();

		List<OmsStation> s = omsCharStationService.getStationsByCoord(x, y, distance);

		retJsons.setList(s);
		return retJsons;
	}


	/**
	 * 根据坐标查询最近的n个站点
	 */
	public JsonForList getStationByLocation(GenericRecord request) throws Exception
	{
		
		//经度
		String x = request.get("x").toString();
		if(StringUtil.isBlank(x)){
			throw new Exception("call parameter error:x:"+x );
		}
		//纬度
		String y = request.get("y").toString();
		if(StringUtil.isBlank(y)){
			throw new Exception("call parameter error:y:"+y );
		}
		//查找数量
		String number = request.get("number").toString();
		if(StringUtil.isBlank(number)){
			throw new Exception("call parameter error:cityCode:"+number );
		}
		
		JsonForList retJsons = new JsonForList<>();

		List<Map<String, Object>> s = omsCharStationService.getStationByLocation(x, y, number);

		retJsons.setList(s);
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		return retJsons;
	}
	
	/**
	 * 通过站点名称、城市代码,模糊匹配查找站点
	 */
	public JsonForList getStationByName(GenericRecord request) throws Exception
	{
		//查找的站点名称
		String stationName = request.get("name").toString();
		if(StringUtil.isBlank(stationName)){
			throw new Exception("call parameter error:stationName:"+stationName );
		}
		//城市代码：市
		String cityCode = request.get("cityCode").toString();
//		if(StringUtil.isBlank(cityCode)){
//			throw new Exception("call parameter error:cityCode:"+cityCode );
//		}
		JsonForList retJsons = new JsonForList<>();

		List<Map<String, Object>> s = omsCharStationService.getStationByName(stationName, cityCode);

		retJsons.setList(s);
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		return retJsons;
	}
	
	/**
	 * 用户对站点评分
	 */
	public JsonCommon<String> scoreStation(GenericRecord request) throws Exception
	{
		
		//用户ID
		String userId = request.get("userId").toString();
		if(StringUtil.isBlank(userId)){
			throw new Exception("call parameter error:userId:"+userId );
		}
		
		//站点ID
		String stationId = request.get("stationId").toString();
		if(StringUtil.isBlank(stationId)){
			throw new Exception("call parameter error:stationId:"+stationId );
		}
		
		//查找的站点名称
		String scoreStr = request.get("score").toString();
		if(StringUtil.isBlank(scoreStr)){
			throw new Exception("call parameter error:scoreStr:"+scoreStr );
		}
		Float score = Float.parseFloat(scoreStr);
		//查找的站点名称
		String scoreTimeStr = request.get("scoreTime").toString();
		if(StringUtil.isBlank(scoreTimeStr)){
			throw new Exception("call parameter error:scoreTimeStr:"+scoreTimeStr );
		}
		Date scoreTime = StringUtil.StrToDate(scoreTimeStr);
  
		OmsStationScore  omsStationScore =new OmsStationScore();
		omsStationScore.setUser_id(userId);
		omsStationScore.setStation_id(stationId);
		omsStationScore.setScore(score);
		omsStationScore.setScore_time(scoreTime);
		
		JsonCommon<String> json = new JsonCommon();
		json.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		json.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		
		try {
			omsCharStationService.addStationScore(omsStationScore);
		} catch (Exception e) {
			log.debug(e.getMessage());
			json.setCode(MsgCodeEnum.SYSTEM_ERROR.getMsgCode());
			json.setMsg(MsgCodeEnum.SYSTEM_ERROR.getMsgInfo());
		}
		
		return json;
	}

	/**
	 * 查询所有运营商
	 */
	public JsonForList getAllOperator(GenericRecord request) throws Exception
	{
		JsonForList<OmsOperationSpListEntity> json = new JsonForList<>();

		List<OmsOperationSpListEntity> s = omsOperationSpListRepo.findByValidFlag(1);

		json.setList(s);
		return json;
	}
}